//
//  ILClearCachFile.m
//  ILife
//
//  Created by lanou on 15/10/31.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILClearCachFile.h"

@implementation ILClearCachFile


// 计算单个文件大小
- (CGFloat)fileSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size;
    }
    return 0;
}

// 计算目录大小（cachs文件夹下的数据和缓存的图片）
- (CGFloat)folderSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:path]) {
        return 0;
    }
    
    NSEnumerator *childFilesEnumerator = [[fileManager subpathsAtPath:path] objectEnumerator];
    NSString *fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    
    folderSize = folderSize/1024.0/1024.0 + [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
    
    return folderSize;
    
}


// 显示缓存
- (CGFloat)showCachs
{
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(13, 1, 1)firstObject];
    return [self folderSizeAtPath:cachPath];
}


// 清理缓存
- (void)clearCachs
{
    
        NSFileManager *manager = [NSFileManager defaultManager];
        
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(13, 1, 1) lastObject];
        
        NSArray *files = [manager subpathsAtPath:cachPath];
        
        NSLog(@"files:%lu",(unsigned long)[files count]);
        
        for (NSString *p in files) {
            NSError *error;
            
            NSString *path = [cachPath stringByAppendingPathComponent:p];
            
            if ([manager fileExistsAtPath:path]) {
                [manager removeItemAtPath:path error:&error];
            }
        }
        [[SDImageCache sharedImageCache] clearDisk];
        
        [self performSelectorOnMainThread:@selector(clearCachSueecss) withObject:nil waitUntilDone:YES];
        
}


// 清理成功
- (void)clearCachSueecss
{
    NSLog(@"清理成功");
    
    UIAlertView * alertView = [[ UIAlertView alloc ] initWithTitle : @" 提示 " message : @" 缓存清理完毕 " delegate : nil cancelButtonTitle : @" 确定 " otherButtonTitles : nil ];
    
    [alertView show];
}


@end
